package com.handinfo.android.ui.window;

import java.io.DataInputStream;

import android.graphics.Bitmap;

import com.handinfo.android.DWGameManager;
import com.handinfo.android.core.net.GameProtocol;
import com.handinfo.android.game.Cell;
import com.handinfo.android.game.Role;
import com.handinfo.android.game.item.ItemConstants;
import com.handinfo.android.ui.IUIWindows;
import com.handinfo.android.ui.UIWindows;
import com.handinfo.android.uicontrols.DWControlsManager;
import com.handinfo.android.uicontrols.DWDragListener;
import com.handinfo.android.uicontrols.DWListener;
import com.handinfo.android.uicontrols.DWLongListener;
import com.handinfo.android.uicontrols.controls.DWBackground;
import com.handinfo.android.uicontrols.controls.DWButton;
import com.handinfo.android.uicontrols.controls.DWControl;
import com.handinfo.android.uicontrols.controls.DWFrame;
import com.handinfo.android.uicontrols.controls.DWGrid;
import com.handinfo.android.uicontrols.controls.DWGrids;
import com.handinfo.android.uicontrols.controls.DWImageBox;
import com.handinfo.android.uicontrols.controls.DWListSubItem;
import com.handinfo.android.uicontrols.controls.DWListbox;
import com.handinfo.android.uicontrols.controls.DWMessageBox;
import com.handinfo.android.uicontrols.controls.DWTextbox;
import com.handinfo.android.uicontrols.controls.DWTitle;
import com.handinfo.android.utils.Tools;

public class UIWarehouse implements IUIWindows
{
	private static final byte[] BAG_TYPE = { Cell.TYPE_COLUMN_ROLEBAG, Cell.TYPE_COLUMN_WAREHOUSE };
	private static final String[] BUTTONMSG = { "背包", "仓库" };
	private Bitmap img_close;
	private Bitmap img_lock;
	private Bitmap img_cell;
	private Bitmap img_button;
	private Bitmap img_anxia;
	private Bitmap img_itemButton;
	private Bitmap img_itemAnxia;
	private Bitmap img_background;
	private Bitmap img_bagTitle;
	private Bitmap img_warehoseTitle;
	private DWGrid selectControl;

	private Cell[][] m_column = new Cell[2][];

	public void init()
	{
		img_close = UIWindows.createImage("/img/newui/fanhuianniu_1.gnp");
		img_lock = UIWindows.createImage("/img/newui/beibaost_1.gnp");
		img_cell = UIWindows.createImage("/img/newui/wupinlan.gnp");
		img_button = UIWindows.createImage("/img/newui/anniu_1.gnp");
		img_anxia = UIWindows.createImage("/img/newui/anniu_1ax.gnp");
		img_background = UIWindows.createImage("/img/newui/beibaobj_2.gnp");
		img_bagTitle = UIWindows.createImage("/img/newui/beibao_1.gnp");
		img_warehoseTitle = UIWindows.createImage("/img/newui/cangku_1.gnp");
		img_itemButton = UIWindows.createImage("/img/newui/anniu_2.gnp");
		img_itemAnxia = UIWindows.createImage("/img/newui/anniu_2ax.gnp");
	}

	public void open(byte index)
	{
		initDate();
		initFrame();
		DWControlsManager.getInstance().addControl(m_warehose);
	}

	public void close(byte index)
	{
		DWControlsManager.getInstance().removeControl(m_warehose);
	}

	public void dispose()
	{
	}

	public void logic()
	{
	}

	private DWFrame m_warehose;
	private DWTitle[] m_title = new DWTitle[2];
	private DWImageBox m_close;
	private DWBackground[] m_background = new DWBackground[2];
	private DWGrids[] m_grids = new DWGrids[2];
	private DWButton[] m_button = new DWButton[2];

	private void initFrame()
	{
		if (m_warehose != null && DWControlsManager.getInstance().contains(m_warehose))
		{
			DWControlsManager.getInstance().removeControl(m_warehose);
			m_warehose = null;
			//刷新界面
		}
		m_warehose = new DWFrame(DWFrame.FRAME_TYPE_FULL);

		m_title[0] = new DWTitle("背包", m_warehose);
		m_title[0].setShowWideHigh(m_warehose.getShowWidth() / 2 + 8, m_title[0].getShowHeight());
		m_title[0].setNearAnchor(m_warehose, Tools.RIGHT_BOTTOM, Tools.RIGHT_TOP, 8, 20);
		m_title[0].setBackground(img_bagTitle, false);
		m_warehose.addControl(m_title[0]);

		m_title[1] = new DWTitle("仓库", m_warehose);
		m_title[1].setShowWideHigh(m_warehose.getShowWidth() / 2 + 8, m_title[1].getShowHeight());
		m_title[1].setBackground(img_warehoseTitle, false);
		m_title[1].setNearAnchor(m_warehose, Tools.LEFT_BOTTOM, Tools.LEFT_TOP, -8, 20);
		m_warehose.addControl(m_title[1]);

		m_close = new DWImageBox(img_close);
		m_close.setNearAnchor(m_title[0], Tools.RIGHT_VCENTER, Tools.RIGHT_VCENTER);
		m_close.setTouchZoomIn(UIFixWindow.TOUCHZOOM, UIFixWindow.TOUCHZOOM);
		m_close.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				close((byte) 0);
			}
		});
		m_warehose.addControl(m_close);

		for (int i = 0; i < 2; i++)
		{
			m_background[i] = new DWBackground((m_warehose.getShowWidth() - 80) / 2, m_warehose.getShowHeight() - 55
					- img_button.getHeight());
			m_background[i].setNearAnchor(m_warehose, (i == 0 ? Tools.LEFT_VCENTER : Tools.RIGHT_VCENTER),
					Tools.HCENTER_VCENTER, (i == 0 ? 20 : -20), -img_button.getHeight() / 4);
			m_warehose.addControl(m_background[i]);
		}

		int gridsX = (m_background[0].getShowWidth() - img_cell.getWidth() * 5 - 30) / 5;
		int gridsY = (m_background[0].getShowHeight() - img_cell.getWidth() * 4 - 40) / 4;

		for (int i = 0; i < 2; i++)
		{
			final int index = i;
			m_grids[i] = new DWGrids(img_cell, Role.COLUMN_MAX_SIZE[BAG_TYPE[i]], 5, 4);
			m_grids[i].setInterspace(gridsX, gridsY);
			m_grids[i].setNearAnchor(m_background[i], Tools.HCENTER_VCENTER, Tools.HCENTER_VCENTER);
			setGrids(i, m_column[i]);
			addGridListener(m_grids[i], index);
			m_warehose.addControl(m_grids[i]);

			m_button[i] = new DWButton("整理" + BUTTONMSG[i], img_button);
			m_button[i].setDownImage(img_anxia);
			m_button[i].addListener(new DWListener() {
				public void OnDoubleClick()
				{
				}

				public void OnClick()
				{
					m_button[index].setFailureTime(30);
					Tools.debugPrintln("整理背包 -> actionTrim");
					DWGameManager.getInstance().getSendMessage().sendArrangeMentColumnCommand(BAG_TYPE[index]);
				}
			});
			m_button[i].setNearAnchor(m_background[i], i == 0 ? Tools.RIGHT_TOP : Tools.LEFT_TOP,
					i == 0 ? Tools.RIGHT_BOTTOM : Tools.LEFT_BOTTOM, 0, 10);
			m_warehose.addControl(m_button[i]);
		}

	}

	private void initDate()
	{
		if (DWGameManager.getInstance().m_role != null)
		{
			m_column[0] = DWGameManager.getInstance().m_role.m_column_bag;
			m_column[1] = DWGameManager.getInstance().m_role.m_column_warehouse;
		}
	}

	/**
	 * 添加格子中的内容
	 */

	private void setGrids(final int num, final Cell[] cell)
	{
		if (cell == null)
			return;

		if (DWGameManager.getInstance().m_role != null) {

			m_grids[num].setGridsImage(img_cell, 0, cell.length - 1);
			m_grids[num].setGridsImage(img_lock, cell.length,
					Role.COLUMN_MAX_SIZE[BAG_TYPE[num]] - 1);

			for (int i = 0; i < cell.length; i++) {
				m_grids[num].m_grids.get(i).m_data = cell[i];
			}
		}
	}

	/**
	 * 添加格子监听
	 */
	private DWMessageBox msg;

	private void addGridListener(final DWGrids grids, final int type)
	{
		grids.addListener(new DWListener() {

			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				DWGrid flaggrid = grids.getTouchGrid();

				if (selectControl != null && (!flaggrid.equals(selectControl)))
				{
					selectControl.setSelect(false);
				}
				selectControl = flaggrid;

				DWGrid grid = grids.getTouchGrid();
				if (grid.m_data != null)
				{
					if (type == 0)
					{
						if (((Cell) grid.m_data).m_item != null)
						{
							showItemMessage((Cell) grid.m_data, UIWindows.getInstance().m_bag.getButtonMenuList(
									UIBag.BAG_STATE_NORMAL, (Cell) grid.m_data));
						}
					}
					else
					{
						showItemMessage((Cell) grid.m_data, null);
					}
				}
				else
				{
					int openNum = grids.getTouchIndex() + 1 - m_column[type].length;
					Role role = DWGameManager.getInstance().m_role;
					long price = (type == 0 ? role.m_bag_unitPrice : role.m_warehouse_unitPrice / 10000);

					msg = new DWMessageBox("提示", "你确定花费"
							+ (openNum * price) + (type == 0 ? "元宝" : "万金币") + "开启" + openNum + "个"
							+ BUTTONMSG[type] + "格子");
					msg.addListener(new DWListener() {
						public void OnDoubleClick()
						{
						}

						public void OnClick()
						{
							DWControlsManager.getInstance().removeControl(msg);
							if (msg.getResult() == DWMessageBox.SOFTKEY_OK)
							{
								actionKuorong(BAG_TYPE[type], grids.getTouchIndex());
							}
						}
					});
					DWControlsManager.getInstance().addControl(msg);
				}
			}
		});
		grids.addDragListener(new DWDragListener() {

			public void OnDrag(DWControl control)
			{
				if (control instanceof DWGrids)
				{
					DWGrids in_grids = (DWGrids) control;
					if (grids.equals(in_grids))
					{
						DWGameManager.getInstance().addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B, "不能进行移动操作");
					}
					else
					{
						if (grids.getDragGird().m_data == null)
						{
							DWGameManager.getInstance().addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B, "不能进行移动操作");
						}
						else
						{
							Cell fromCell = (Cell) (in_grids.getTouchGrid().m_data);
							Cell endCell = (Cell) (grids.getDragGird().m_data);
							actionMove(fromCell, endCell);
						}
					}
				}
			}
		});

		grids.addLongListener(new DWLongListener() {

			public void OnLong(boolean isDown)
			{
				DWGrid flaggrid = grids.getTouchGrid();

				if (selectControl != null && (!flaggrid.equals(selectControl)))
				{
					selectControl.setSelect(false);
				}
				selectControl = flaggrid;
				selectControl = grids.getTouchGrid();
			}
		});
	}

	/**
	 * 显示物品详情及功能
	 */
	private DWFrame showFrame;

	private void showItemMessage(final Cell cell, final String[] buttonMenu)
	{
		if (cell == null || cell.m_item == null)
			return;

		if (showFrame != null && DWControlsManager.getInstance().contains(showFrame))
		{
			DWControlsManager.getInstance().removeControl(showFrame);
			showFrame = null;
		}

		Cell m_bag_cell_equip = DWGameManager.getInstance().m_role.m_column_equip[cell.m_item.m_subtype];
		int showWidth = ((DWGameManager.Screen_Width * 5) >> 4) + 50;
		if (buttonMenu != null && cell.m_item.m_type == ItemConstants.道具类型_装备 && m_bag_cell_equip.m_item != null)
		{
			showFrame = new DWFrame(showWidth * 2,
					showWidth);
			Tools.debugPrintln("………………………………………………装备对比…………………………………………");
		}
		else
		{
			showFrame = new DWFrame(showWidth, showWidth);
		}
		showFrame.setClickClose(false);
		showFrame.setBackgroundColor(Tools.ALPHA);

		DWBackground itemBackground = new DWBackground(img_background, showFrame.getShowWidth(), showFrame
				.getShowHeight());
		itemBackground.setNearAnchor(showFrame, Tools.HCENTER_VCENTER, Tools.HCENTER_VCENTER);
		showFrame.addControl(itemBackground);

		DWImageBox close=new DWImageBox(img_close);
		close.addListener(new DWListener() {				
			public void OnDoubleClick()
			{
			}
			
			public void OnClick()
			{
				DWControlsManager.getInstance().removeControl(showFrame);
			}
		});
		close.setNearAnchor(showFrame, Tools.HCENTER_VCENTER, Tools.RIGHT_TOP);
		close.setTouchZoomIn(UIFixWindow.TOUCHZOOM, UIFixWindow.TOUCHZOOM);
		showFrame.addControl(close);
		
		int listHeight = 0;
		if (buttonMenu == null)
		{
			listHeight = showFrame.getShowHeight() - 20 - img_itemButton.getHeight();
		}
		else
		{
			listHeight = showFrame.getShowHeight() - 30 - img_itemButton.getHeight() * 2;
		}
		DWListbox itemList = new DWListbox(showFrame.getShowWidth() - 20, listHeight - 10);
		itemList.setShowBackgroundRect(false);
		itemList.setNearAnchor(showFrame, Tools.HCENTER_TOP, Tools.HCENTER_TOP, 0, 10);
		showFrame.addControl(itemList);

		DWListSubItem itemSubItem = new DWListSubItem();
		int anchorx = 0;
		if (showFrame.getShowWidth() > showWidth)
		{
			UIWindows.getInstance().m_bag.getItemWindow(itemSubItem, showWidth, m_bag_cell_equip.m_item);
			DWTextbox message = new DWTextbox("<mark c=FFBB11>已装备</mark>");
			message.setNearAnchor(itemSubItem, Tools.LEFT_TOP, Tools.LEFT_TOP, 20, 0);
			itemSubItem.addControls(message);
			anchorx = showFrame.getShowWidth() >> 1;
		}
		UIWindows.getInstance().m_bag.getItemWindow(itemSubItem, anchorx, 0, showWidth, cell.m_item);
		itemList.addSubItem(itemSubItem);

		//添加移动按钮
		DWButton itemButton = new DWButton("移动", img_button);
		itemButton.setDownImage(img_anxia);
		itemButton.setNearAnchor(itemList, Tools.HCENTER_TOP, Tools.RIGHT_BOTTOM, -showWidth / 2,
				buttonMenu == null ? 10 : img_itemButton.getHeight() + 15);
		itemButton.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				DWControlsManager.getInstance().removeControl(showFrame);
				showFrame = null;
				//移动
				int endIndex = 0;
				if (cell.m_column_type == Cell.TYPE_COLUMN_ROLEBAG)
				{
					endIndex = 1;
				}

				Cell endCell = getExchangCell(m_column[endIndex]);

				if (endCell == null)
				{
					DWGameManager.getInstance().addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B,
							BUTTONMSG[endIndex] + "已满，请清理后再进行操作");
				}
				else
				{
					actionMove(cell, endCell);
				}
			}
		});
		showFrame.addControl(itemButton);

		//添加功能按钮
		if (buttonMenu != null)
		{
			DWButton[] m_item_button = new DWButton[buttonMenu.length];

			int item_button_x = (showWidth - img_itemButton.getWidth() * buttonMenu.length)
					/ (buttonMenu.length * 2);

			if (buttonMenu != null && buttonMenu.length > 0) {
				for (int i = buttonMenu.length - 1; i >= 0; i--) {
					final int buttonID = i;
					m_item_button[i] = new DWButton(buttonMenu[i], img_itemButton);
					m_item_button[i].setDownImage(img_itemAnxia);
					if (i == buttonMenu.length - 1) {
						m_item_button[i]
								.setNearAnchor(itemList, Tools.RIGHT_TOP, Tools.RIGHT_BOTTOM, -item_button_x, 5);
					}
					else
					{
						m_item_button[i].setNearAnchor(m_item_button[i + 1], Tools.RIGHT_VCENTER, Tools.LEFT_VCENTER,
								-(item_button_x << 1), 0);
					}

					m_item_button[i].addListener(new DWListener() {

						public void OnDoubleClick()
						{
						}

						public void OnClick()
						{
							if (cell.m_item != null) {
								DWControlsManager.getInstance().removeControl(showFrame);
								showFrame = null;
								UIWindows.getInstance().m_bag.ItemKeyListener(cell, buttonID, buttonMenu);
							}
						}
					});

					showFrame.addControl(m_item_button[i]);
				}
			}
		}
		DWControlsManager.getInstance().addControl(showFrame);
	}

	/**
	 * 刷新界面数据
	 * @param type
	 */
	public void updateWindow(byte type)
	{
		if (m_warehose == null || (!DWControlsManager.getInstance().contains(m_warehose)))
			return;

		int updateIndex = -1;
		switch (type) {
			case Cell.TYPE_COLUMN_ROLEBAG:
				updateIndex = 0;
				break;
			case Cell.TYPE_COLUMN_WAREHOUSE:
				updateIndex = 1;
				break;
		}

		if (updateIndex > -1)
		{
			initDate();
			setGrids(updateIndex, m_column[updateIndex]);
		}
	}

	/**
	 * 获取第一个空的格子
	 * @param cellArray 格子数组
	 * @return
	 */
	private Cell getExchangCell(Cell[] cellArray)
	{
		Cell getCell = null;

		if (cellArray != null)
		{
			for (Cell cell : cellArray) {
				if (cell.m_item == null)
				{
					getCell = cell;
					break;
				}
			}
		}

		return getCell;
	}

	/**
	 * 移动
	 * 
	 * @param item
	 */
	private void actionMove(Cell fromCell, Cell toCell)
	{
		Tools.debugPrintln("移动道具 -> actionMove");
		DWGameManager.getInstance().getSendMessage().sendExchangeCellCommand((byte) fromCell.m_column_type,
				fromCell.m_index, (byte) toCell.m_column_type, toCell.m_index);
	}

	/**
	 * 扩容
	 */
	private void actionKuorong(byte type, int index)
	{
		Tools.debugPrintln("扩容道具 -> actionKuorong");
		DWGameManager.getInstance().getSendMessage().sendOperaterCellMenuCommand(GameProtocol.操作菜单_扩充栏, type, index);
	}

	public void recvOpenWarehouse(DataInputStream dis)
	{
		try {
			byte state = dis.readByte();
			if (state == 1)
			{
				DWControlsManager.getInstance().removeOtherControl();
				open((byte) 0);
			}
			else
			{
				DWGameManager.getInstance().addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B, "仓库开启失败");
			}
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}
}
